package cn.itsource.util;

import cn.itsource.domain.SysUser;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/** 
 * 用户信息工具类
 */
public class UserTools {

    //获取当前登录用户的ID
    public static Long getCurrentUserId(){
        SysUser userInfo = getUserInfo();
        return userInfo.getId();
    }

    public static  HttpServletRequest getRequest(){
        //理解作用：这么写就能拿到request对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request;
    }

    //获取当前登录用户的真实姓名
    public static String getCurrentUserRealName(){
        SysUser userInfo = getUserInfo();
        return userInfo.getRealName();
    }

    //把用户信息存入session
    public static void saveUserSession( SysUser user){
        //理解作用：这么写就能拿到request对象
        HttpSession session = getRequest().getSession();
        session.setAttribute(BlogConstant.LOGIN_SESSION, user);
    }

    //从session中获取用户信息
    public static SysUser getUserInfo(){

        HttpSession session = getRequest().getSession();
        Object attribute = session.getAttribute(BlogConstant.LOGIN_SESSION);
        return (SysUser) attribute;
    }
}